import { setPosition, setTransfrom } from "../action/newTransfrom.js";
import { options, Options, state } from "../config.js";
import { box, currentRole, currentState, domg } from "../index.js";
import { emit, on } from "../utils/scoket.js";
import { closeMask, openMask, setMaskContent } from "./mask.js";

const app = document.querySelector("#app") as HTMLDivElement;
//弹幕功能
let count = 0;
export const barrageFun = ({ key }: KeyboardEvent) => {
  if (key !== "t") return;
  count++;
  if (count >= 20) {
    openMask();
    openBarrage(app);
    count = 0;
  }
};
//弹幕面板的模板
const template = `    
<div class="barrageBox">
  <div class="row">
    <input class="barrageIpt" />
  </div>
  <div class="row">
    <button class="barrageBiu">发射</button>
  </div>
</div>`;

const openBarrage = (app: HTMLDivElement) => {
  setMaskContent(template);
  //获取焦点以及回车发送
  setTimeout(() => {
    let ipt = domg(".barrageIpt") as HTMLInputElement;
    ipt.focus();
    ipt.onkeydown = function ({ key }) {
      if (key === "Enter") return domg(".barrageBiu").click();
    };
  }, 500);
  domg(".barrageBiu").onclick = () => {
    const ipt = domg(".barrageIpt") as HTMLInputElement; //拿到ipt内容
    closeMask();
    createBarrage(ipt.value, app, options);
  };
};

on.all("/barrage", ({ value }) => {
  if (value.role !== currentState.role) {
    createBarrage(value.str, app, value);
  }
});

/**
 *
 * @param str 创建弹幕的内容
 * @param ele 在那个地方创建弹幕
 */
const createBarrage = (str: string, ele: HTMLDivElement, options: Options) => {
  //根据弹幕类型生成弹幕
  options.role ||
    emit.all(currentState.role, "/barrage", {
      role: currentState.role,
      str,
      ...options,
    }); //发送请求
  switch (options.type) {
    //滚动弹幕
    case "rolling":
      rollingBarrage(str, ele, options);
      break;
  }
};

function rollingBarrage(str: string, ele: HTMLElement, options: Options) {
  const head = options.role || state.roleName;
  //创建弹幕实体
  const barrage = document.createElement("div");
  barrage.classList.add("barrage");
  barrage.style.display = "inline-block";
  barrage.style.color = options.barrageColor; //弹幕字体颜色
  barrage.style.backgroundColor = options.bgc;
  barrage.innerText = head + " : " + str;
  //弹幕生成位置
  const po = {
    x: box.boxW - 100,
    y: Math.floor(Math.random() * (box.boxH + 60) - 26),
  };
  setPosition(barrage, po);
  ele.append(barrage);
  barrage.getBoundingClientRect;
  let barrageW = barrage.offsetWidth;

  //创建弹幕
  let timer: any;
  timer = setInterval(() => {
    if (po.x <= -barrageW) return clearInterval(timer);
    po.x -= options.barrageSpeed;

    setPosition(barrage, po);
  }, 100);
}
